import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

class ValueNotifierStatefulWidget extends StatefulWidget {
  const ValueNotifierStatefulWidget({Key? key}) : super(key: key);

  @override
  State<ValueNotifierStatefulWidget> createState() => _ValueNotifierStatefulWidgetState();
}

class _ValueNotifierStatefulWidgetState extends State<ValueNotifierStatefulWidget> {
  //
  final ValueNotifier<int> _myValueNotifier = ValueNotifier<int>(0); //初始值为 0

  @override
  Widget build(BuildContext context) {
    print('build');
    return Scaffold(
      appBar: AppBar(
        title: const Text('ValueNotifier 示例'),
      ),
      body: Center(
        //ValueListenableBuilder 继承自 StatefulWidget
          child: ValueListenableBuilder<int>(
              valueListenable: _myValueNotifier, //valueListenable 表示一个可监听的数据源
              builder: (BuildContext context, int value, Widget? child) {
                print('builder');
                //builder 只会在 value 值变化时被调用，此处的 value 就是 _myValueNotifier 管理的值发生变化后的新值
                return Text('count: ${_myValueNotifier.value}');
              })),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          _myValueNotifier.value++; //数据变化时触发 ValueListenableBuilder 重新构建
        },
        child: const Icon(Icons.add),
      ),
    );
  }

  @override
  void dispose() {
    _myValueNotifier.dispose();
    super.dispose();
  }
}

